// packageRecruit/pages/create-basic-info/create-basic-info.js
import {
    workDetailEcho,
    establishWork,
    editWork
} from '../../api/recruit'
import {
    getBindCompanySupplier
} from '../../../api/app.js'
import user from '../../../utils/user'
import {
    toast,
    confirm,
    getLocation
} from '../../../utils/util'
import global from '../../../utils/global'
Page({
    /**
     * 页面的初始数据
     */
    data: {
        textAreaHeight: 22,
        formworkHeight: 20,
        workMoney: '',
        salaryTypeList: ['元/时', '元/日', '元/周', '元/月'],
        salaryType: '元/时',
        jobId: '',
        templateList: '',
        templateIndex: 0,
        isMapShow: false,
        tipList: false,
        info: {
            hostId: '', // 父
            childrenId: '', // 子
            jobName: '',
            workLatitude: '', // 工作经纬度
            workLongitude: '', // 工作经纬度
            workAddress: '', // 工作地点
            district: '', // 地区
            city: '', // 城市
            serveCompanyId: '',
            serveCompanyName: '',
            tempFile: [], // 在列表页面传递过来的文件数据 后续继续上传的文件也会放到这里
            templateList: '', // 模板
            template: '请输入工作内容',
            workMoney: '', // 新增待遇金额,
            jobTag: []
        },
        again: {
            id: ''
        },
        files: [],
        userLocation: false,
        text: '',
    },

    async onLoad(options) {
        console.log(options, 'options')
        if (options.type === 'edit') {
            wx.setNavigationBarTitle({
                title: '编辑岗位'
            })
            this.setData({
                jobId: options.jobid
            })
            this.getWorkDetailEcho()
        }

        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', ((data) => {
            this.setData({
                ['info.tempFile']: data.fileList
            })
        }))
        if (this.data.info.tempFile.length > 0) {
            this.setData({
                ['info.jobName']: '',
            })
        } else {
            this.setData({
                jobId: options.jobid
            })
        }
    },
    onReady() {

    },

    onShow() {
        // 获取是否开启定位
        wx.getSetting({
            success: async (res) => {
                ['scope.userLocation']
                console.log(res.authSetting['scope.userLocation'], 'res')
                if (!res.authSetting['scope.userLocation']) {
                    this.setData({
                        userLocation: false
                    })
                } else {
                    this.setData({
                        userLocation: true
                    })
                }
            }
        })
    },
    // 点击标签添加#号
    onAddLabel() {
        // 点击#标签按钮 时 拼接一个#号上去
        this.setData({
            ['info.template']: this.data.info.template += '#',
            text: this.data.text += '#',
        })
        // 再次清洗
        this.setData({
            ['info.template']: this.data.text.replace(/#[1-9|\u4e00-\u9fa5|A-Z|a-z]{1,}/g, function (word) {
                return '<span style="color:#3E5FF5">' + word + '</span>'
            })
        })
        // 在input输入回车时 替换成 br标签
        this.data.info.template = this.data.info.template.replace(/[\r\n]/g, '<br/>')
        this.setData({
            // 由于rich-text标签 在外部不包裹div的话 他不会溢出换行 所以拼接 div标签
            ['info.template']: '<div style="width:100%;height:auto;word-break:break-all;line-height:1.4;font-size:22rpx;">' + this.data.info.template + '</div>',
        })
        console.log(this.data.text, 'texttext')
        console.log(this.data.info.template, 'template')
    },
    // 多行文本框输入
    textareaInpun(event) {
        console.log(event, 'event')
        this.setData({
            text: event.detail.value
        })
        const query = wx.createSelectorQuery()
        console.log(query.select('#formwork'), '获取的标签')
        query.select('#rich-text').boundingClientRect(res => {
            this.setData({
                textAreaHeight: (res.height + (28 * 1.4))
            })
            console.log(this.data.height, '改变后的 高度')
        }).exec()
        // 先把  符合#号开头空格结尾 拼接 span标签改变颜色
        this.setData({
            ['info.template']: event.detail.value.replace(/#[1-9|\u4e00-\u9fa5|A-Z|a-z]{1,}/g, function (word) {
                return '<span style="color:#3E5FF5">' + word + '</span>'
            })
        })
        // 在input输入回车时 替换成 br标签
        this.data.info.template = this.data.info.template.replace(/[\r\n]/g, '<br/>')
        this.setData({
            // 由于rich-text标签 在外部不包裹div的话 他不会溢出换行 所以拼接 div标签
            ['info.template']: '<div style="width:100%;height:auto;word-break:break-all;line-height:1.4;font-size:22rpx;">' + this.data.info.template + '</div>',
            // 保留一份原数据传递给后端
            text: event.detail.value,
            // 吧符合标签的内容清洗出来 渲染到页面上
            ['info.jobTag']: event.detail.value.match(/#[1-9|\u4e00-\u9fa5|A-Z|a-z]{1,}/g)
        })
    },
    // 获取公司列表
    created() {
        getBindCompanySupplier({
            type: 0,
            companyId: user.companyId,
        }).then(res => {
            this.setData({
                tipList: res,
                repeatList: res
            })
        })
    },
    // 取消选择企业
    cancelTapEnter() {
        if (this.data.tipList.length > 0) {
            this.setData({
                tipList: false
            })
        }
    },
    // 选择企业
    tapEnter(event) {
        console.log(event, 'event')
        this.setData({
            tipList: false,
            ['info.serveCompanyId']: event.currentTarget.dataset.id,
            ['info.serveCompanyName']: event.currentTarget.dataset.name
        })
    },
    // 筛选企业
    onEnterInput(event) {
        console.log(event, 'event')
        if (!event.detail.value) {
            this.setData({
                repeatList: this.data.tipList
            })
        }
        // includes
        const data = JSON.parse(JSON.stringify(this.data.tipList))
        // item.children = item.children.filter((ite,ind)=>ite.name.includes(event.detail.value))
        const list = data.filter(item => item.serveCompanyName.includes(event.detail.value))
        console.log(list, 'list')
        console.log(data, 'data')
        this.setData({
            repeatList: list
        })
    },
    // 进入管理创建企业
    onGoEnterprise() {
        wx.navigateTo({
            url: '/pages/enterprise/enterprise',
        })
        this.cancel()
    },
    // 输入标题
    onTitleInput(event) {
        console.log(event, 'event')
        this.setData({
            ['info.jobName']: event.detail.value,
        })
    },
    // 文件删除 
    onDelete(event) {
        let {
            index
        } = event.currentTarget.dataset
        this.data.info.tempFile.splice(index, 1)
        this.setData({
            ['info.tempFile']: this.data.info.tempFile
        })
    },
    // 图片放大
    onPreview(event) {
        const {
            url
        } = event.currentTarget.dataset
        wx.previewImage({
            urls: [url]
        })
    },
    // 播放视频
    onPlay(event) {
        const {
            i
        } = event.currentTarget.dataset
        const imageList = []
        this.data.info.tempFile.forEach(ite => {
            if (ite.fileType === 'video') {
                imageList.push({
                    url: ite.tempFilePath || ite.fileUrl,
                    type: 'video'
                })
            } else {
                imageList.push({
                    url: ite.tempFilePath || ite.fileUrl,
                    type: 'image'
                })
            }
        })
        wx.previewMedia({
            sources: imageList,
            current: i
        })
    },
    // 上传视频
    onUploadFile() {
        wx.chooseMedia({
            count: 1,
            // maxDuration: 20,
            sizeType: ['original', 'compressed'],
            success: (res) => {
                if (res.tempFiles[0].duration > 15) {
                    toast('视频长度最长15秒')
                    return
                }
                let faile = []
                faile.push(...this.data.info.tempFile)
                faile.push(res.tempFiles[0])
                if (faile.length > 9) {
                    toast('最多上传9个')
                    return
                }
                this.setData({
                    ['info.tempFile']: faile
                })
            },
            fail: () => {
                toast('上传失败请重试')
            }
        })
    },

    // 上一步
    onBack() {
        wx.navigateBack({
            delta: 1
        })
    },
    // 下一步
    async onNext() {
        if (!this.data.info.jobName) {
            toast('请输入标题')
            return
        }
        if (!this.data.info.serveCompanyName) {
            toast('请选择企业')
            return
        }
        if (!this.data.info.workAddress) {
            toast('请选工作地点')
            return
        }
        if (/[\D]/.test(this.data.workMoney)) {
            toast('薪资仅支持输入数字')
            return
        }
        if (this.data.workMoney <= 0) {
            toast('金额不可小于等于0')
            return
        }
        console.log(this.data.info.tempFile, 'tempFiletempFile')
        this.uploadFile(this.data.info.tempFile)
        // wx.redirectTo({
        //     url: '/packageRecruit/pages/work-job-detail/work-job-detail?jobid=' + res,
        // })
        // wx.navigateTo({
        //     url: '/packageRecruit/pages/create-details-info/create-details-info',
        //     success:(res)=>{
        //         res.eventChannel.emit('createBasicInfo',  this.data.info )
        //     }
        // })
    },
    // 岗位回显
    getWorkDetailEcho() {
        console.log(this.data.jobId, 'jobId')
        workDetailEcho({
            jobId: this.data.jobId
        }).then(res => {
            console.log(res, 'res')

            this.setData({
                ['info.jobName']: res.jobName,
                ['info.workLatitude']: res.jobLocation.split(',')[1],
                ['info.workLongitude']: res.jobLocation.split(',')[0],
                ['info.workAddress']: res.jobAddress,
                ['info.city']: res.city,
                ['info.district']: res.district,
                ['info.serveCompanyId']: res.serveCompanyId,
                ['info.serveCompanyName']: res.serveCompanyName,
                ['info.tempFile']: res.params.jobFile || [],
                ['info.templateList']: res.templateContent,
                ['info.type']: 'edit',
                ['info.jobId']: this.data.jobId,
                workMoney: res.salary,
                salaryType: res.jobSalaryType,
                ['info.template']: res.jobDetail.replace(/#[1-9|\u4e00-\u9fa5|A-Z|a-z]{1,}/g, function (word) {
                    return '<span style="color:#3E5FF5">' + word + '</span>'
                }),
            })
            // 在input输入回车时 替换成 br标签
            this.data.info.template = this.data.info.template.replace(/[\r\n]/g, '<br/>')
            this.setData({
                ['info.template']: '<div style="width:100%;height:auto;word-break:break-all;">' + this.data.info.template + '</div>',
                text: res.jobDetail,
                ['info.jobTag']: res.jobDetail.match(/#[1-9|\u4e00-\u9fa5|A-Z|a-z]{1,}/g)
            })
            const query = wx.createSelectorQuery()
            console.log(query.select('#formwork'), '获取的标签')
            query.select('#rich-text').boundingClientRect(res => {
                this.setData({
                    textAreaHeight: (res.height + (28 * 1.4))
                })
                console.log(this.data.height, '改变后的 高度')
            }).exec()
        })
    },
    // 地图选点
    getMapselect() {
        console.log('getMapselect')
        getLocation().then(res => {
            wx.chooseLocation({
                latitude: res.latitude,
                longitude: res.longitude,
                fail(err) {
                    console.log(err, 'err')
                },
                success: (mapRes) => {
                    let province = mapRes.address.slice(0, mapRes.address.indexOf('省') + 1) + '-' + mapRes.address.slice(mapRes.address.indexOf('省') + 1)
                    let city = province.slice(0, province.indexOf('市') + 1) + '-' + province.slice(province.indexOf('市') + 1)
                    let area = city.slice(0, city.indexOf('区') + 1) + '-' + city.slice(city.indexOf('区') + 1)
                    console.log(area.split('-'), 'area')
                    this.setData({
                        ['info.workLatitude']: mapRes.latitude,
                        ['info.workLongitude']: mapRes.longitude,
                        ['info.workAddress']: mapRes.address,
                        ['info.city']: area.split('-')[1],
                        ['info.district']: area.split('-')[2]
                    })
                }
            })
        })
    },
    // 选择薪资类型
    onSalaryType(event) {
        console.log(event.detail.value, 'event')
        this.setData({
            salaryType: this.data.salaryTypeList[(Number(event.detail.value))]
        })
    },
    // 创建岗位
    establishWorkPost() {
        this.againAssignment()
        establishWork(this.data.again).then(async res => {
            await toast('创建成功')
            wx.redirectTo({
                url: '/packageRecruit/pages/work-job-detail/work-job-detail?jobid=' + res,
            })
        })
    },
    // 文件批量上传
    async uploadFile(tempFiles) {
        console.log(tempFiles, 'tempFiles上传的文件')
        const t = this
        const uploadedFile = []
        const notUploaded = []
        tempFiles.forEach(item => {
            if (item.tempFilePath) {
                notUploaded.push(item)
            } else {
                uploadedFile.push(item)
            }
        })
        console.log(uploadedFile, notUploaded)
        wx.showLoading({
            title: '文件上传中',
            mask: true
        })
        let promise = Promise.all(notUploaded.map((item) => {
            return new Promise((resolve) => {
                wx.uploadFile({
                    url: global.baseUrl + global.zpUrl + '/api/v2/zp/job/upload-file',
                    filePath: item.tempFilePath,
                    name: 'file',
                    header: {
                        'Authorization': 'Wx ' + global.token
                    },
                    success(res) {
                        console.log('上传成功', res.data)
                        resolve(res.data)
                    },
                    fail(rej) {
                        console.log(rej, 'rej')
                    }
                })
            })
        }))
        promise.then(async res => {
            console.log(res, 'resresres')
            const files = []
            await res.forEach(item => {
                const url = JSON.parse(item).data.fileUrl
                const size = JSON.parse(item).data.fileSize
                let type = 'photo'
                if (
                    /(mp4|flv|mov|wmv|avi|mpeg|rmvb)$/.test(url.toLowerCase())
                ) {
                    console.log(type)
                    type = 'video'
                }
                files.push({
                    fileUrl: url,
                    fileType: type,
                    fileSize: size
                })
                console.log('提交成功0')

            })
            uploadedFile.push(...files)
            await t.setData({
                files: uploadedFile
            })
            console.log(uploadedFile, 'uploadedFile')
            console.log(this.data.files, 'files')
            wx.hideLoading()
            // 判断是创建还还是编辑
            if (!this.data.jobId) {
                console.log('创建')
                await this.establishWorkPost()
            } else {
                console.log('编辑')
                await this.setEditWork()
            }
        })
    },
    // 编辑岗位
    async setEditWork() {
        await this.againAssignment()
        console.log(this.data.again, 'again')
        editWork(this.data.again).then(async () => {
            await toast('修改成功')
            wx.navigateBack({
                delta: 1
            })
            // wx.redirectTo({
            //     url: '/packageRecruit/pages/work-job-detail/work-job-detail?jobid=' + this.data.superiorInfo.jobId,
            // })
        })
    },
    againAssignment() {
        this.setData({
            ['again.id']: this.data.jobId,
            ['again.serialNumber']: (user.userId + '' + new Date().getTime()), // 序列号
            ['again.jobName']: this.data.info.jobName, // 工作标题
            ['again.serveCompanyName']: this.data.info.serveCompanyName, // 企业名称
            ['again.jobAddress']: this.data.info.workAddress, // 工作地点
            ['again.city']: this.data.info.city, // 城市
            ['again.district']: this.data.info.district, // 地区
            ['again.serveCompanyId']: this.data.info.serveCompanyId, // 企业id
            ['again.jobDetail']: this.data.text, // 工作内容
            ['again.jobLocation']: this.data.info.workLongitude + ',' + this.data.info.workLatitude, // 拼接经纬度
            ['again.jobSalaryType']: this.data.salaryType, // 新增类型
            ['again.salary']: this.data.workMoney, // 薪资金额
            ['again.jobTag']: this.data.info.jobTag ? this.data.info.jobTag.join(';') : '', // 标签
            ['again.params.photos']: this.data.files // 上传的附件
        })
        console.log(this.data.again, 'again')
    }
})